import { Prisma } from '@prisma/client';
import prisma from '@/server/lib/prisma';
import { UserSchema2 } from '@/server/lib/zodSchema';
import { encryptAES } from '@/server/lib/md5';

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    UserSchema2.parse(body); // 校验参数

    // 校验用户名是否重复
    const isUserName = await prisma.sys_user.findFirst({
      where: {
        userId: {
          not: Number(body.userId)
        },
        userName: body.userName
      }
    })
    if (isUserName) {
      return {
        code: 400,
        msg: '用户名已存在',
      }
    }

    // 参数
    const data: Prisma.sys_userUpdateInput = {
      deptId: body.deptId,
      userName: body.userName,
      nickName: body.nickName,
      email: body.email,
      phonenumber: body.phonenumber,
      sex: body.sex,
      status: body.status,
      remark: body.remark,
    }
    if (body.password) {
      const password = encryptAES(body.password);
      data.password = password;
    }
    const result = await prisma.sys_user.update({
      where: {
        userId: Number(body.userId)
      },
      data,
      include: {
        posts: true,
        roles: true
      }
    });

    if (body.roles && Array.isArray(body.roles)) {
      const createData: any = [];
      body.roles.map((roleId: number) => {
        createData.push({
          userId: Number(body.userId),
          roleId: roleId,
        })
      })
      await prisma.sys_user_role.deleteMany({
        where: {
          userId: Number(body.userId)
        },
      });
      await prisma.sys_user_role.createMany({
        data: createData
      })
    }

    if (body.posts && Array.isArray(body.posts)) {
      const createData: any = [];
      body.posts.map((postId: number) => {
        createData.push({
          userId: Number(body.userId),
          postId: postId,
        })
      })
      await prisma.sys_user_post.deleteMany({
        where: {
          userId: Number(body.userId)
        },
      });
      await prisma.sys_user_post.createMany({
        data: createData
      })
    }

    return {
      code: 200,
      data: result,
      msg: '更新成功'
    }
  } catch (error: any) {
    const err = JSON.parse(error);
    return {
      code: 400,
      msg: err[0].message || '未知错误'
    }
  } finally {
    await prisma.$disconnect(); // 关闭连接
  }
})
